<template>
  <!-- 业务员详情 -->
  <div class="details">
    <mt-header fixed title="专栏详情">
      <router-link to slot="left">
        <mt-button icon="back" v-if="iosShow" @click="$router.go(-1)"
          >返回</mt-button
        >
      </router-link>
      <!-- <mt-button icon="more" slot="right"></mt-button> -->
    </mt-header>
    <div class="details_top">
      <img src="../../../static/image/currentduan.png" class="back" />
      <div class="details_nav">
        <div>
          <img src="../../../static/image/logotwo.png" />
        </div>
        <div>税东家(国际)税务商学院</div>
      </div>
    </div>
    <div class="details_oitem">
      <div class="details_img">
        <img :src="imgUrl" />
      </div>
      <div class="details_txt">{{ name }}</div>
      <div class="details_two">
        <span>简介</span>
        <span>{{ content }}</span>
      </div>
    </div>

    <div class="topTabSwiper">
      <div class="tab">目录</div>
    </div>
    <div class="swiper_con">
      <div class="more_list">
        <div class="more_li" v-for="(item, index) in goodsList" :key="index">
          <span>{{ item.title }}</span>
        </div>
      </div>
    </div>
    <div class="bottom" v-if="isBuy == 1">
      <button class="subscription" @click="gostart(redirectUrl)">去学习</button>
    </div>
    <div class="bottom" v-else>
      <button class="subscription" @click="Paymoney()">
        订阅
        <span>￥{{ price }}</span>
      </button>
    </div>
  </div>
</template>
<script>
import {
  columnDetail,
  Reqpay,
  Sdksig,
  codeh5,
  wxLoginone,
} from "../../api/api";
import querystring from "query-string";
import { Header, Indicator, Toast } from "mint-ui";

export default {
  name: "Catalog",
  data() {
    return {
      imgUrl: "",
      name: "",
      content: "",
      goodsList: "",
      isBuy: "",
      price: "",
      columnId: "",
      redirectUrl: "",
      GoodId: "",
      pwd: "",
      nowtime: "",
      url: "",
      signature: "",
      queryList: "",
      iosShow: false,
    };
  },
  created() {
    let href = window.location.href;
    console.log(href);
    if (href.includes("/?code")) {
      //url包括 com/?code 证明为从微信跳转回来的
      let sp1 = href.split("/?code=");
      let code = sp1[1].split("&")[0];
      console.log(code);
      this.CodeH(code);
    }
    if (localStorage.getItem("token")) {
      console.log("已登录");
      //  console.log(this.$route.query);
      // this.queryList = this.$route.query;
      // console.log(this.queryList);
    } else {
      if (this.$route.query.code == null || this.$route.query.code == "") {
        console.log(this.$route.query);
        this.queryList = this.$route.query;
        console.log(this.queryList);
        this.Codeshare();
      } else {
        this.queryList = this.$route.query;
        let code = this.$route.query.code;
        localStorage.setItem("code", code);
      }
      // this.Codeshare();
    }
    this.Phonetype();
    console.log(this.$route.query.code);
    // this.columnId = this.$route.query.columnId;
    console.log(this.$route.query);
    this.columnDetail();
    this.randomString();
    this.getTime();
    // this.Codeshare();
    // alert(location.href.split("#")[0], 111);
    // var url = location.href;
    // if (location.hash.length) {
    //   this.url = url.substr(0, url.indexOf(location.hash));
    // }
  },
  methods: {
    columnDetail() {
      Indicator.open("加载中...");
      var params = {
        columnId: this.columnId,
      };
      if (
        this.$route.query.columnId != null &&
        this.$route.query.columnId != ""
      ) {
        params = {
          columnId: this.$route.query.columnId,
        };
      }
      params = querystring.stringify(params);
      var a = localStorage.getItem("token");
      a = JSON.parse(a);
      columnDetail(params, a).then((res) => {
        console.log(res.data);
        if (res.data.code == 1) {
          this.imgUrl = res.data.data.imgUrl;
          this.name = res.data.data.name;
          this.content = res.data.data.content;
          this.goodsList = res.data.data.goodsList;
          this.name = res.data.data.name;
          this.isBuy = res.data.data.isBuy;
          this.price = res.data.data.price;
          this.redirectUrl = res.data.data.redirectUrl;
          this.GoodId = res.data.data.columnId;
          Indicator.close();
        } else {
          Toast(res.data.message);
          Indicator.close();
        }
      });
    },
    //判断是安卓还是ios
    Phonetype() {
      let ua = navigator.userAgent;
      console.log(ua); //Ios终端
      //Android终端
      //let isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
      // console.log(isAndroid)
      let isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (!isiOS) {
        this.iosShow = true;
      }
    },
    //微信登录
    Codeshare() {
      let appid = "wxc74ae6a677c8b11d";
      let redirect_uri = encodeURIComponent(
        `https://xcy.shuidongjia.net/#/Salesman/catalog?columnId=${this.queryList.columnId}&id=${this.queryList.id}&branchId=${this.queryList.branchId}&roleCode=${this.queryList.roleCode}&time=${this.nowtime}`
      );
      // `https://xcy.shuidongjia.net/?from=singlemessage#/Salesman/catalog?columnId=${this.queryList.columnId}&id=${this.queryList.id}&branchId=${this.queryList.branchId}&roleCode=${this.queryList.roleCode}`
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
      // wxLoginone().then(res => {
      //   console.log(res);
      // });
      console.log(localStorage.getItem("code"));
      this.CodeH(localStorage.getItem("code"));
    },
    //获取微信给的code
    CodeH(codeVal) {
      console.log(codeVal);
      localStorage.setItem("code", codeVal);
      let that = this;
      let params = {
        code: codeVal,
        rc: this.$route.query.roleCode,
        ds: this.$route.query.id,
        branchId: this.$route.query.branchId,
      };
      console.log(params);
      params = querystring.stringify(params);
      codeh5(params).then((res) => {
        if (res.data.code == 1) {
          localStorage.setItem("token", JSON.stringify(res.data.data.token));
          localStorage.setItem("user", JSON.stringify(res.data.data.user));
          // if (localStorage.getItem("user")) {
          //   let newUser = JSON.parse(localStorage.getItem("user"));
          //   if (newUser.roleCode === "center") {
          //     this.$router.push({ name: "Ghome" });
          //   }
          //   if (newUser.roleCode === "salesman") {
          //     this.$router.push({ name: "Catalog" });
          //   }
          //   if (newUser.roleCode === "branch") {
          //     this.$router.push({ name: "Bhome" });
          //   }
          // }
          this.columnDetail();
        } else {
          Toast(res.data.message);
        }
      });
    },
    getTime() {
      //new Date() new一个data对象，当前日期和时间
      //toLocaleString() 方法可根据本地时间把 Date 对象转换为字符串，并返回结果。
      this.nowtime = Math.round(new Date().getTime() / 1000).toString();
      //this.nowtime = new Date().getTime();
      console.log(this.nowtime);
    },
    randomString(len) {
      len = len || 32;
      var $chars =
        "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length;
      var pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      console.log(pwd);
      this.pwd = pwd;
    },
    //微信分享
    wxInit() {
      let that = this;
      let newUser = JSON.parse(localStorage.getItem("user"));
      let id = newUser.id;
      console.log(id);
      let branchId = newUser.branchId;
      let roleCode = newUser.roleCode;
      console.log(branchId, roleCode);
      if (branchId == null) {
        branchId = 0;
        console.log(branchId);
      }
      // var ds = JSON.parse(localStorage.getItem("user")).xiaoeUserId;
      // console.log(ds)
      var stateObject = {};
      // var title = '';
      // var newUrl = '';
      let url = window.location.href.split("#")[0];
      //   console.log(url)
      //    url = url.split('#')[0] + '#' + `/Salesman/catalog?columnId=${that.$route.query.columnId}&id=${id}&branchId=${branchId}&roleCode=${roleCode}`
      // console.log(url)
      //   let links =  url.split('#')[0] + '/static/html/redirect.html?app3Redirect=' + encodeURIComponent(url);
      //   console.log(links)
      // console.log(encodeURIComponent(url));
      // url = encodeURIComponent(url);
      let links = `${url}#/Salesman/catalog?columnId=${that.$route.query.columnId}&id=${id}&branchId=${branchId}&roleCode=${roleCode}`;
      // links = encodeURIComponent(links)
      // ?columnId='+that.$route.query.columnId

      console.log(links);
      console.log(location.toString().indexOf("?") == "-1");
      if (location.toString().indexOf("?") == "-1") {
        links = window.location.href;
        console.log(links);
      } else {
        // links = encodeURI(
        //   location.href.split("?")[0] + "#" + location.href.split("#")[1]
        // );
        console.log(links);
      }
      window.history.pushState(stateObject, links);

      let params = {
        noncestr: that.pwd,
        timestamp: that.nowtime,
        url: links,
      };
      params = querystring.stringify(params);
      Sdksig(params).then((res) => {
        that.signature = res.data.data.signature;
        //  if (location.href.includes('/catalog')){
        //        let id = location.href.split('?')[1].split('=')[1];
        //        console.log(id);
        //         url = `${location.origin}#/catalog?columnId=${id}`
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: "wxc74ae6a677c8b11d", // 必填，公众号的唯一标识
          timestamp: that.nowtime, // 必填，生成签名的时间戳
          nonceStr: that.pwd, // 必填，生成签名的随机串
          signature: that.signature, // 必填，签名
          jsApiList: [
            "onMenuShareTimeline", // 分享到朋友圈
            "onMenuShareAppMessage", // 分享到微信好友
            "onMenuShareQQ", // 分享到QQ
            "onMenuShareWeibo", // 分享到微博
            "onMenuShareQZone", // 分享到空间
            "hideMenuItems", // 批量隐藏菜单
            "scanQRCode",
            "translateVoice",
            "updateTimelineShareData",
          ], // 必填，需要使用的JS接口列表
        });
        //微信分享
        wx.ready(function () {
          //分享到朋友圈
          wx.onMenuShareTimeline({
            title: that.name, // 分享时的标题
            link: links, // 分享时的链接
            imgUrl: that.imgUrl, // 分享时的图标
            success: function () {
              Toast("分享成功");
            },
            cancel: function () {
              Toast("取消分享");
            },
          });
          wx.onMenuShareAppMessage({
            title: that.name, // 分享时的标题
            link: links, // 分享时的链接
            imgUrl: that.imgUrl, // 分享时的图标
            success: function () {
              Toast("分享成功");
            },
            cancel: function () {
              Toast("取消分享");
            },
          });
          // wx.error(function(res) {
          //   // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
          //   alert("errorMSG:" + JSON.stringify(res.data));
          // });
          // console.log(that.name)
          //分享给朋友
        });
        //  }else{
        //      url = `${location.origin}#/` // 正常的重定向链接
        //  }
        //  url = encodeURIComponent(url)
        //  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc74ae6a677c8b11d&redirect_uri=${url}?response_type=code&scope=snsapi_base&state=123`
      });
    },

    //支付
    Paymoney() {
      let that = this;
      that.bus.$emit("loading", true); //开始
      let params = {
        price: parseInt((that.price * 100).toFixed(10)),
        goodsId: that.GoodId,
        payType: 1,
      };
      params = querystring.stringify(params);
      let a = localStorage.getItem("token");
      a = JSON.parse(a);
      Reqpay(params, a).then((res) => {
        if (res.data.code == 0) {
          Toast("订阅失败");
          that.bus.$emit("loading", false); //结束
        } else {
          if (parseInt((that.price * 100).toFixed(10)) == 0) {
            that.columnDetail();
          } else {
            //根据prepayid调用bridge进行支付
            WeixinJSBridge.invoke(
              "getBrandWCPayRequest",
              {
                appId: res.data.data.appId,
                //    //公众号名称，由商户传入
                timeStamp: res.data.data.timeStamp,
                //    //时间戳，自1970年以来的秒数
                nonceStr: res.data.data.nonceStr,
                paySign: res.data.data.sign,
                //    //随机串
                package: res.data.data.package,
                signType: res.data.data.signType,
              },
              function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                  //使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  that.columnDetail();
                } else {
                  Toast("未知错误，交易中止");
                }
              }
            );
          }
        }
        // }
        that.bus.$emit("loading", false); //结束
      });
    },
    //去学习
    gostart(redirectUrl) {
      window.location.href = redirectUrl;
    },
    lala() {
      let user = JSON.parse(localStorage.getItem("user"));
      user.roleCode = "salesman";
      let a = localStorage.setItem("user", JSON.stringify(user)); // alert(localStorage.setItem("user", user))
      if (JSON.parse(localStorage.getItem("user").roleCode == "salesman")) {
        this.$router.push({ name: "Sahomepage" });
      }
    },
  },
  mounted() {
    this.wxInit();
  },
};
</script>
<style lang="scss" scoped>
/* 业务详情 */
.mint-header {
  background: #ffffff;
  color: #333333;
}
.details {
  width: 100%;
  height: auto;
  padding-top: 40px;
  padding-bottom: 1.2rem;
}

.details_top {
  width: 100%;
  height: 1.75rem;
  position: relative;
  overflow: hidden;
}

.details_top .back {
  width: 100%;
  height: 1.75rem;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}

.details_nav {
  position: absolute;
  left: 0.31rem;
  top: 0.6rem;
  // bottom: 0.23rem;
  height: auto;
  display: flex;
  text-align: center;
}

.details_nav div:nth-of-type(1) {
  width: 0.82rem;
  height: 0.82rem;
  border-radius: 50%;
  overflow: hidden;
}

.details_nav div:nth-of-type(1) img {
  width: 0.82rem;
  height: 0.82rem;
}

.details_nav div:nth-of-type(2) {
  font-size: 0.4rem;
  color: #fff;
  margin-left: 0.23rem;
  margin-top: 0.15rem;
}

.details_oitem {
  width: 100%;
  height: auto;
}

.details_img {
  width: 100%;
  height: auto;
  box-sizing: border-box;
}

.details_img img {
  width: 100%;
  height: auto;
  height: 100%;
}

.details_txt {
  width: 7.22rem;
  height: auto;
  min-height: 1rem;
  border-bottom: 0.02rem solid #ddd;
  // line-height: 1.09rem;
  font-size: 0.34rem;
  color: #222;
  font-weight: bold;
  margin-left: 0.26rem;
  display: flex;
  align-items: center;
}

.details_two {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  border-bottom: 0.2rem solid #eeeeee;
}

.details_two span:nth-child(1) {
  font-size: 0.34rem;
  color: #222;
  margin-left: 0.28rem;
  display: block;
  margin-top: 0.2rem;
}

.details_two span:nth-child(2) {
  display: block;
  width: 6.75rem;
  height: auto;
  font-size: 0.26rem;
  color: #666;
  line-height: 0.38rem;
  margin-top: 0.15rem;
  margin-bottom: 0.55rem;
  margin-left: 0.35rem;
}
.tab {
  width: 100%;
  box-sizing: border-box;
  height: 0.89rem;
  line-height: 0.89rem;
  font-size: 0.28rem;
  color: #666666;
  padding-left: 0.35rem;
  border-bottom: 0.02rem solid #dddddd;
}

.swiper_con {
  width: 100%;
  height: auto;
}

.more_list {
  width: 6.84rem;
  height: auto;
  margin-left: 0.33rem;
}

.more_li {
  width: 100%;
  height: 1.1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.26rem;
  margin-top: 0.3rem;
  box-sizing: border-box;
  border: 0.02rem solid #cfcfcf;
  color: #333333;
  border-radius: 0.16rem;
}

.more_li span:nth-child(1) {
  // width: 4.26rem;
  padding-left: 0.3rem;
  height: auto;
  // overflow: hidden;
  // text-overflow: ellipsis;
  // white-space: nowrap;
}

.more_li img {
  width: 0.25rem;
  height: 0.35rem;
  margin-right: 0.31rem;
}
.more_li div {
  width: 1.34rem;
  height: 0.46rem;
  background: #fef3e0;
  border-radius: 0.23rem;
  color: #999999;
  font-size: 0.2rem;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding-left: 0.27rem;
  margin-right: 0.19rem;
}
.more_li div img {
  width: 0.15rem;
  height: 0.21rem;
  margin-right: 0.07rem;
}
.bottom {
  width: 100%;
  height: 1rem;
  position: fixed;
  bottom: 0;
  left: 0;
}
.bottom .subscription {
  width: 100%;
  height: 1rem;
  border: none;
  outline: none;
  background: #ffb400;
  display: flex;
  align-items: center;
  font-size: 0.34rem;
  padding: 0;
  border-radius: 0;
  color: #ffffff;
  justify-content: center;
}

.pop {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.pop .pop_message {
  width: 6rem;
  height: 6.68rem;
  background: #fff;
  border-radius: 0.2rem;
}

.pop_message img {
  width: 5rem;
  height: 5rem;
  margin-left: 0.45rem;
  margin-top: 0.25rem;
}

.pop_message div {
  width: 5.5rem;
  margin-left: 0.75rem;
  height: 1rem;
  font-size: 0.28rem;
}
</style>